# -*- coding:utf-8 -*-
"""
@Author : 审心
@Time : 2023/3/23 9:42
任务线程类
"""
import json
import os
import sys
import threading
import traceback
import pythoncom
import time
from datetime import datetime, timedelta

from common import glv
from common.logger.log import log_, create_file_log, flush_file_log
from common.utils.Base64Util import file_to_base64
from request.open.robot import update_status, append_task_statement_result
from config import data as config
from config.core.keys import ROBOT_NUMBER
from autoTask.core.taskMapping import task_mapping


class TaskThread(threading.Thread):

    def __init__(self, task_snapshot):
        """
        初始化任务线程
        :param task_snapshot:  任务快照
        """
        threading.Thread.__init__(self),
        self.task_snapshot = task_snapshot
        self._stop_event = threading.Event()

    def run(self):
        try:
            pythoncom.CoInitialize()
            start_task(self.task_snapshot)
        except:
            log_.error("启动线程时异常")
        finally:
            pythoncom.CoUninitialize()

    def stop(self):
        self._stop_event.set()


def start_task(task_snapshot):
    try:
        execute_task(task_snapshot)
        log_.info("所有任务执行结束")
    except:
        log_.error(f"任务启动异常 : {sys.exc_info()[0]} {sys.exc_info()[1]}")
        log_.error(traceback.format_exc())
    finally:
        glv.set_item("task_thread", None)
        update_status(config.get("robot.number"), 1)



def execute_task(task_snapshot):
    for snapshot in task_snapshot:
        task_result = {}
        # 默认任务状态为以结束
        task_status = 2
        if isinstance(snapshot, str):
            snapshot = json.loads(snapshot)
        file_handler = create_file_log(f"{snapshot.get('taskName')}.log", log_)
        err_msg = None
        try:
            log_.info(f"任务快照 : {snapshot}")
            # 更新机器状态为执行任务中
            update_status(config.get(ROBOT_NUMBER), 2, snapshot["statementId"], snapshot["taskId"],
                          snapshot["taskName"])
            # 访问指定的任务方法
            if 'param' in snapshot:
                result = task_mapping[str(snapshot["taskId"])](snapshot)
            else:
                result = task_mapping[str(snapshot["taskId"])](None)
            if result is not None:
                task_result = result
            log_.info(f"任务结束 : {snapshot['taskName']}", )
        except:
            # 设置任务状态为已失败
            task_status = 3
            err_msg = sys.exc_info()[1]
            log_.error(f"任务执行时异常 : {err_msg}")
            log_.error(traceback.format_exc())
        finally:
            #  最后追加任务报表
            try:
                # 输出日志至文件
                flush_file_log(log_, file_handler)
                # 转为base64上传
                task_log_base64 = file_to_base64(file_handler.baseFilename, is_remove=True)
                append_task_statement_result(snapshot["statementId"], task_status
                                             , task_file_base64=task_result.get("task_file_base64"),
                                             task_file_suffix=task_result.get("task_file_suffix"),
                                             task_log_base64=task_log_base64, errMsg=err_msg)
            except:
                log_.error(f"任务追加报表时异常 : {sys.exc_info()[0]} {sys.exc_info()[1]}")
                log_.error(traceback.format_exc())
            time.sleep(5)
